from sys import stdin
import json
import base64
import gzip
import os
import time

def decode_base64_and_gunzip(encoded_string):
    # Decode the base64 string to bytes
    decoded_bytes = base64.b64decode(encoded_string)
    
    # Decompress the bytes using gzip
    decompressed_bytes = gzip.decompress(decoded_bytes)
    
    # Convert the decompressed bytes to a string
    result_string = decompressed_bytes.decode('utf-8')
    return result_string


def clear_screen():
    # For Windows
    if os.name == 'nt':
        _ = os.system('cls')
    # For macOS and Linux (POSIX systems)
    else:
        _ = os.system('clear')

clear_screen()

# with open("init_main.c", "r") as f:
#     src_list=list(f.read())
src_list = None

line_idx = 0;
for line in stdin:
    print(f"{line_idx}: ", end="")
    if line[0] == "#":
        continue

    try:
        editing_event = json.loads(line.strip())
        print(editing_event)
        ts = editing_event["timestamp"]
        action = editing_event["actionType"]
        position = editing_event["charPosition"]
        filename = editing_event["filename"]
        old_text = editing_event["oldText"]
        changes = editing_event["newText"]
        
        position = int(position)
        # changes = eval(changes)
        # print(position, changes)
        if action == "INSERT":
            src_list[position:position] = list(changes)
        elif action == "DELETE":
            del src_list[position:position+len(old_text)]
        elif action == "SNAPSHOT":
            new_src_list = list(decode_base64_and_gunzip(old_text))
            if src_list is None:
                src_list = new_src_list
            else:
                # compare current src_list with new_src_list
                if src_list == new_src_list:
                    print(f"matched at {ts}")
                else:
                    current = "".join(src_list)
                    new_src = "".join(new_src_list)
                    raise RuntimeError(f"not matching at {ts}:\ncurrent:\n{current}\n\nnew src:\n{new_src}")
        elif action == "UPDATE":
            del src_list[position:position+len(old_text)]
            src_list[position:position] = list(changes)
        else:
            raise RuntimeError(f"Unknown action {action}")
    except ValueError:
        print(f"error: {line}")
    finally:
        print("".join(src_list))
        print("######")

    line_idx +=1
    # time.sleep(1)
    # clear_screen()

print("########: reconstructed")
print("".join(src_list))

